// @ts-nocheck
import { useState, useEffect } from 'react'

enum RESPONSE_STATUS_CODES {
  SUCCESS = '0000'
}

const REQUEST_DELAY_TIME = 1000 * 1

const debounce = (fn, delay, immediate = false) => {
  let tid
  return immediate
    ? function () {
      const context = this;
      const args = arguments;
      if (tid) clearTimeout(tid);
      const callNow = !tid;
      tid = setTimeout(function () {
        tid = null;
      }, delay);
      if (callNow) fn.apply(context, args);
    }
    : function () {
      const context = this;
      const args = arguments;
      if (tid) clearTimeout(tid);
      tid = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    };
};

// 参数 --更改--> 请求 --防抖--> 返回 --同步--> 状态
export const useFetch = (callService, defaultParams, defaultResponse, delay = REQUEST_DELAY_TIME) => {
  const [params, query] = useState(defaultParams)
  const [response, setResponse] = useState(defaultResponse)
  useEffect(() => {
    let ignore = false
    const request = debounce((params) => {
      callService(params)
        .then(res => {
          if (!ignore) {
            if (res?.code == RESPONSE_STATUS_CODES.SUCCESS) {
              if (res?.data) {
                setResponse(res?.data)
              }
            }
          }
        })
    }, delay, true)
    request(params)
    return () => {
      ignore = true
    }
  }, [params])

  return { query, params, response }
}